package com.dependencies.springdatajpa.service;

import com.dependencies.springdatajpa.entity.Geographic;
import com.dependencies.springdatajpa.repository.GeographicRepository;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhizhou   2024/9/24 09:55
 */
@Service
public class GeographicService {
    
    @Autowired
    private GeographicRepository geographicRepository;
    
    /**
     * 递归获取行政区划数据
     * @param parentId 父级ID，根节点传入null或0
     * @return 行政区划列表
     */
    public List<Geographic> getGeographicListData(Long parentId) {
        List<Geographic> list = geographicRepository.findByParentId(parentId);
        for (Geographic geographic : list) {
            // 递归获取子节点
            List<Geographic> children = getGeographicListData(geographic.getId());
            geographic.setChildren(children);
        }
        return list;
    }
    
    //批量查询：一次性查询所有数据，并在内存中构建树结构
    public List<Geographic> getGeographicListDataAll(Long parentId) {
        List<Geographic> allGeographics = geographicRepository.findAll();
        return buildTree(allGeographics, parentId);
    }
    
    private List<Geographic> buildTree(List<Geographic> all, Long parentId) {
        List<Geographic> tree = new ArrayList<>();
        for (Geographic geo : all) {
            if (geo.getParentId().equals(parentId)) {
                geo.setChildren(buildTree(all, geo.getId()));
                tree.add(geo);
            }
        }
        return tree;
    }
    
}
